/*
 * em_406a.c
 *
 *  Created on: Jun 22, 2011
 *      Author: ben
 */

#include <avr/io.h>

#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "em_406a.h"

void GPSInit(uint16_t ubrr_value)
{
	UBRR0L = ubrr_value;
	UBRR0H = (ubrr_value >> 8);
	UCSR0B = (1 << RXEN0) | (1 << TXEN0);
	UCSR0C = (1 << USBS0) | (1 << UCSZ01) | (1 << UCSZ00);
}

char GPSRead()
{
	while (!(UCSR0A & (1 << RXC0))) {}
	return UDR0;
}

GPS_DATA processGGA(char buffer[NMEA_BUFFER_SIZE])
{
	GPS_DATA gpsData;
	char *endptr;
//	double degrees, minutesfrac;
	int i = 0;
	if (buffer[i] == ',')
		i++;

	//UTC Time [hhmmss.sss]
	gpsData.fix_time = strtod(&buffer[i], &endptr);
	while(buffer[i++] != ',');

	//Latitude [ddmm.mmmmm]
	gpsData.latitude = strtod(&buffer[i], &endptr);
//	gpsData.latitude = 41.324722;
//	minutesfrac = modf(gpsData.latitude/100, &degrees);
//	gpsData.latitude = degrees + (minutesfrac*100)/60;
	gpsData.latitude = gpsData.latitude/100;
	while(buffer[i++] != ',');

	//North/South
	if (buffer[i] == 'S')
	{
		gpsData.latitude = -gpsData.latitude;
		gpsData.NS = 'S';
	}
	else
		gpsData.NS = 'N';
	while(buffer[i++] != ',');

	//Longitude [ddmm.mmmmm]
	gpsData.longitude = strtod(&buffer[i], &endptr);
//	gpsData.longitude = 105.570556;
//	minutesfrac = modf(gpsData.longitude/100, &degrees);
//	gpsData.longitude = degrees + (minutesfrac*100)/60;
	gpsData.longitude = gpsData.longitude/100;
	while(buffer[i++] != ',');

	//East/West
	if (buffer[i] == 'W')
	{
		gpsData.longitude = -gpsData.longitude;
		gpsData.EW = 'W';
	}
	else
		gpsData.EW = 'E';
	while (buffer[i++] != ',');

	return gpsData;
}
